<template>
	<view class="wifi wifi-index" style="width: 750rpx;height: 100vh;background-color: whitesmoke;
							  padding-top: 1px;">
		<view class="switch" 
			  style="box-sizing: border-box; width: 700rpx;height: 40px;margin: 20px auto  0;
					 border-radius: 10px;display: flex;align-items: center;
					 justify-content: space-between;background-color: white;box-shadow: 0 0 10px 0 #eee;">
			<view class="label" 
				  style="margin-left: 60rpx;font-weight: bold;">
				无线局域网
			</view>
			<view class="open-switch"
				  style="margin-right: 10px;">
				<switch 
					:checked="switchStatus" 
					@change="switchStatus = !switchStatus" 
				/>
			</view>
		</view>
		<view class="title"
			  style="width: 700rpx;margin: 20px auto 0;
					 font-size: 12px;color: #aaa;display: flex;
					 align-items: center;">
			当前选择的配网wifi信息
		<!-- 	<view class="getInfo" @click="getConnectedWifi"
				  style="width: 30px;height: 30px;background-color: black;
						 text-align: center;line-height: 30px;
						 margin-left: 10px;border-radius: 50%;color: white;
						 box-shadow: 3px 3px 10px -2px #555, -3px -3px 10px #eee;">
				获取
			</view> -->
		</view>
		<view class="wifi-info" v-if="connectedWifi.SSID"
			  style="box-sizing: border-box;width: 700rpx;margin: 10px auto 0;
			  	   border-radius: 10px;background-color: white;
			  	   box-shadow: 0 0 10px 0 #eee;padding: 10px 15px;">
			<view class="conn-ssid">
				wifi名称: {{connectedWifi.SSID}}
			</view>
			<view class="conn-bssid">
				wifi地址: {{connectedWifi.BSSID}}
			</view>
			<view class="conn-pwd" v-if="connectedWifi.password">
				wifi密码: {{connectedWifi.password}}
			</view>
		</view>
		<view class="title" 
			  style="width: 700rpx;margin: 20px auto 0;
					 font-size: 12px;color: #aaa;">
			可配网wifi
		</view>
		<view 
			style="box-sizing: border-box;width: 700rpx;margin: 10px auto 0;
				   border-radius: 10px;background-color: white;
				   box-shadow: 0 0 10px 0 #eee;">
			<scroll-view
				:scroll-top="scrollTop"
				scroll-y
				class="content-pop"
				>
				<view
					class="itemInfo"
					v-for="(item, index) in wifiList"
					:key="index"
					style="box-sizing: border-box; display: flex;
						   justify-content: space-between;align-items: center;
						   "
					>
					<view style="box-sizing: border-box;margin-left: 60rpx;font-weight: bold;">
						{{ item.SSID }}
					</view>
					<view class="connect-btn" @click="choseWifi(item)"
						  style="box-sizing: border-box;width: 60px;
							     height: 30px;border-radius: 5px;font-weight: bold;
								 text-align: center;line-height: 30px;
								 margin-right: 20px;box-shadow: 3px 3px #666,-3px -3px 10px 0 #eee;">
						选择
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="tip" style="width: 700rpx;margin: 20px auto 0;font-size: 14px;
								 color: #aaa;">
			<text style="font-weight: bold;color: red;font-style: italic;">
				提示:请先确保手机wifi连接到了设备的热点, 再进行配网
			</text> 
			
		</view>
		<view class="send" style="width: 700rpx;margin: 10px auto 0;">
			<view class="send-btn" @click="connectAndSend"
				  style="width: 700rpx;height: 40px;background-color: black;
						 border-radius: 10px;line-height: 40px;text-align: center;
						 color: white;font-weight: bold;box-shadow: 0px 10px 10px -5px #555;">
				配网
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				switchStatus: false,
				wifiList: [],
				connectedWifi: {},
				isConnectSocket: false
			}
		},
		watch: {
			switchStatus(newValue) {
				if(newValue) {
					this.startWifi();
				} else {
					this.stopWifi();
				}
			}
		},
		onLoad() {
			this.getWifiList()
		},
		methods: {
			choseWifi(value) {
				uni.showModal({
					title: "输入当前选择的wifi密码",
					confirmText: '确定',
					cancelText: '关闭',
					editable: true,
					success: (res) => {
						console.log(res)
						if(res.confirm) {
							const password = res.content;
							value.password = password;
							this.connectedWifi = value;
						}
					}
				})
			},
			connectAndSend() {
				if(!this.connectedWifi.SSID) {
					uni.showModal({
						title: '请先选择需要配网的wifi...',
					})
					return;
				}
				this.initSocket();
				uni.showToast({
					title: "配网中...",
					icon: 'loading'
				})
			},
			sendMessage(value) {
				wx.sendSocketMessage({
					data: value,
					success() {
						uni.showToast({
							title: '发送成功, 等待响应...',
							icon: 'loading'
						})
						console.log("发送成功")
					},
					fail() {
						uni.showToast({
							title: '配网失败',
							icon: 'none'
						})
						console.log("发送失败")
					}
				});  
			},
			initSocket() {
				const value = JSON.stringify(this.connectedWifi);
				if(this.isConnectSocket) {
					this.sendMessage(value);
					return;
				}
				wx.connectSocket({  
					url: 'ws://192.168.43.1:8901',
					// url: 'wss://192.168.137.1:8085/websocket',
				    success: (res) => {  
						
				    },  
				    fail: (error) => {  
						uni.showToast({
							title: '配网失败',
							icon: 'none'
						})
						console.log("socket失败")
				    },
					timeout: 2000,
				});  
				  
				// 监听WebSocket连接打开事件  
				wx.onSocketOpen((res) => {
					console.log("socket打开了")
					this.isConnectSocket = true;
					this.sendMessage(value);
				});  
				
				// 监听 websocket 关闭事件
				wx.onSocketClose(() => {
					uni.showToast({
						title: '网络关闭',
						icon: 'none'
					})
					this.isConnectSocket = false;
				})
				  
				// 监听WebSocket错误  
				wx.onSocketError((res) => {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
					console.log("socket错误", res)
					this.isConnectSocket = false;
				});  
				// 监听WebSocket接受到服务器的消息事件  
				wx.onSocketMessage((res) => { 
					console.log(res, "响应")
				}); 
			},
			/** 获取当前连接的wifi */
			getConnectedWifi() {
			  this.connectedWifi = { SSID: '' }
			  if (this.switchStatus !== true) return
			  uni.getConnectedWifi({
			    success: (res) => {
			      console.log('获取当前连接的wifi 成功', res)
			      this.connectedWifi = res.wifi // 当前连接的wifi的信息
			      // this.connectedWifiSSID = res.wifi.SSID
			    },
			    fail: (err) => {
			      console.error('获取当前连接的wifi 失败:', err)
			      uni.showModal({ content: err.errMsg, showCancel: false })
			    },
			  })
			},
			connectWifi(wifiInfo) {
				console.log(wifiInfo, "wifiInfo")
				uni.showModal({
					title: "输入密码",
					confirmText: '连接',
					cancelText: '关闭',
					editable: true,
					success: (res) => {
						console.log(res)
						if(res.confirm) {
							const password = res.content;
							this.connectToWifi(wifiInfo.SSID, password)
						}
					}
				})
			},
			connectToWifi(SSID, password) {
				uni.connectWifi({
					SSID: SSID,
					password: password,
					success: () => {
						uni.onWifiConnected((res) => {
							uni.showToast({
								title: '连接成功',
								icon: 'none'
							})
						})
					},
					fail(error) {
						console.log(error)
						uni.showToast({
							title: '连接失败:' + error.errMsg,
							icon: 'error'
						})
					}
				})
			},
			getWifiList() {
				// 获取手机型号
				const sys = uni.getSystemInfoSync();
				if (sys.platform == "android" && sys.parseInt(sys.system.substr(8)) < 6) {
					this.$tip.error("手机版本不支持");
					return;
				}
				if (sys.platform == "ios" && sys.parseInt(sys.system.substr(4)) < 11.2) {
					this.$tip.error("手机版本不支持");
					return;
				}
			},
			startWifi() {
				uni.startWifi({
					success: (res) => {
						console.log("打开wifi成功", res)
						this.getWifi();
					},
					fail: (err) => {
						if(err.errCode == 12005) {
							uni.showModal({
								title: '请先打开系统wifi'
							})
						}
						this.switchStatus = false;
						console.log("打开wifi失败", err)
					}
				})
			},
			getWifi() {
				uni.getWifiList({
					//成功后，就可以获取列表了
					success: (res) => {
						//列表获取成功后，要到事件里提取
						uni.onGetWifiList((res) => {
							console.log(res, "获取wifi列表成功");
							this.onGetWifiListFun(res);
						});
					},
					fail: (err) => {
						if(err.errCode == 12005) {
							uni.showModal({
								title: '请先打开系统wifi'
							})
						}
						this.switchStatus = false;
						console.log(err, "获取wifi列表失败");
					},
				});
			},
			// 监听获取到的WiFi列表函数 进行处理
			onGetWifiListFun(info) {
				console.log("获取到的wifi信息", info)
				this.wifiList = [];
				let wifiList = [];
				// 过滤掉没有SSID的 还有对信号的处理,用来渲染对应的样式的
				wifiList = info.wifiList.filter((item) => {
					if (item.signalStrength >= -55) {
						item["signalDefine"] = [true, true, true];
					} else if (item.signalStrength >= -66) {
						item["signalDefine"] = [false, true, true];
					} else if (item.signalStrength >= -88) {
						item["signalDefine"] = [false, false, true];
					} else if (item.signalStrength >= -100) {
						item["signalDefine"] = [false, false, false];
					}
					return item.SSID;
				});
				// 按信号强度排序
				wifiList = wifiList.sort((a, b) => {
					return b.signalStrength - a.signalStrength;
				});
				// 取当前连接的WiFi的信号
				const connectResIndex = wifiList.findIndex(
					(item) => item.SSID === this.connectWifi
				);
				const connectRes = wifiList[connectResIndex];
				if (connectRes) {
					this.connectWifiSignal = connectRes["signalDefine"];
					this.connectRes = connectRes;
				}
				wifiList.splice(connectResIndex, 1);

				this.wifiList = this.uniqueByField(wifiList, "SSID");
				// this.$tip.loaded();
			},
			uniqueByField(list, field) {
				const seen = new Set();
				const result = [];

				for (let item of list) {
					const value = item[field];
					if (!seen.has(value)) {
						seen.add(value);
						result.push(item);
					}
				}

				return result;
			},
			stopWifi() {
				uni.stopWifi({
					success: (res) => {
						console.log("关闭wifi成功", res)
					},
					fail: (err) => {
						console.log("关闭wifi失败", err)
					}
				})
			}
		}
	}
</script>

<style>
  .itemInfo {
    height: 96rpx;
    line-height: 96rpx;
    font-size: 28rpx;
    border-bottom: 1rpx solid #f4f4f4;
    text-align: left;
  } 
  .content-pop {
    width: 700rpx;
    max-height: 55vh;
  }
</style>
